package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.res.check.CheckDay_res;
import com.ruoyi.system.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ICheckService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 验收Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-11
 */
@Service
public class CheckServiceImpl implements ICheckService {
    @Resource
    private CheckMapper checkMapper;
    @Resource
    private CheckDetailMapper checkDetailMapper;
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private SpecMapper specMapper;
    @Resource
    private BrandMapper brandMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private DeliveryMapper deliveryMapper;
    @Resource
    private DeliveryDetailMapper deliveryDetailMapper;
    @Resource
    private CateMapper cateMapper;

    /**
     * 查询验收
     *
     * @param id 验收主键
     * @return 验收
     */
    @Override
    public Check selectCheckById(Long id) {
        Check check = checkMapper.selectCheckById(id);

        if (check.getSchoolId() != null) {
            SysDept sysDept = sysDeptMapper.selectDeptById(check.getSchoolId());
            if (sysDept != null) {
                check.setSchoolName(sysDept.getDeptName());
            }
        }
        if (check.getDeptId() != null) {
            SysDept sysDept = sysDeptMapper.selectDeptById(check.getDeptId());
            if (sysDept != null) {
                check.setCompanyName(sysDept.getDeptName());
            }
        }

        List<CheckDetail> checkDetails = checkDetailMapper.selectCheckDetailList(new CheckDetail() {{
            setCheckId(check.getId());
        }});
        checkDetails.forEach(detail -> {
            if (detail.getTypeId() != null) {
                Type type = typeMapper.selectTypeById(detail.getTypeId());
                if (type != null) {
                    detail.setTypeName(type.getName());
                }
            }
            if (detail.getSpecId() != null) {
                Spec spec = specMapper.selectSpecById(detail.getSpecId());
                if (spec != null) {
                    detail.setSpecName(spec.getName());
                }
            }
            if (detail.getBrandId() != null) {
                Brand brand = brandMapper.selectBrandById(detail.getBrandId());
                if (brand != null) {
                    detail.setBrandName(brand.getName());
                }
            }
        });
        check.setDetails(checkDetails);
        return check;
    }

    /**
     * 查询验收列表
     *
     * @param check 验收
     * @return 验收
     */
    @Override
    public List<Check> selectCheckList(Check check) {
        if (check.getParams() != null) {
            if (check.getParams().containsKey("sendTimeStart") && check.getParams().containsKey("sendTimeEnd")) {
                if (check.getParams().get("sendTimeStart") != null && !"".equals(check.getParams().get("sendTimeStart"))
                        && check.getParams().get("sendTimeEnd") != null && !"".equals(check.getParams().get("sendTimeEnd"))) {
                    check.getParams().put("sendTimeStart", check.getParams().get("sendTimeStart") + " 00:00:00");
                    check.getParams().put("sendTimeEnd", check.getParams().get("sendTimeEnd") + " 23:59:59");
                }

            }
        }
        List<Check> checks = checkMapper.selectCheckList(check);
        checks.forEach(item -> {

            if (item.getSchoolId() != null) {
                SysDept sysDept = sysDeptMapper.selectDeptById(item.getSchoolId());
                if (sysDept != null) {
                    item.setSchoolName(sysDept.getDeptName());
                }
            }


        });
        return checks;
    }

    /**
     * 查询验收统计
     */
    @Override
    public List<CheckDay_res> selectCheckDay(Check check) {
        return checkMapper.selectCheckList(check).stream().map(item -> {
            CheckDay_res res = new CheckDay_res();
            SysDept sysDept = sysDeptMapper.selectDeptById(item.getSchoolId());
            if (sysDept != null) {
                res.setSchoolName(sysDept.getDeptName());
            }
            StringBuilder cateStr = new StringBuilder();
            List<Cate> cateList = cateMapper.selectCateByCheck(item.getId());
            if (cateList != null && !cateList.isEmpty()) {
                for (Cate cate : cateList) {
                    cateStr.append(cate.getName()).append(",");
                }
            }
            if (cateStr.indexOf(",") != -1) {
                res.setCheckCate(cateStr.substring(0, cateStr.lastIndexOf(",")));
            } else {
                res.setCheckCate(cateStr.toString());
            }
            return res;
        }).collect(Collectors.toList());
    }

    /**
     * 新增验收
     *
     * @param req 验收
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCheck(DeliveryDetail req) {
        Delivery delivery = deliveryMapper.selectDeliveryById(req.getDeliveryId());
        if (delivery == null) {
            throw new ServiceException("未查询到配送单");
        }

        Check check_search = new Check(req.getDeliveryId(), req.getSendTime());
        List<Check> checks = checkMapper.selectCheckList(check_search);


        //根据报量单和配送时间为单位查询验收记录
//        List<Check> checks_ = checkMapper.selectCheckList(new Check() {{
//            setOrderId(req.getDoseId());
//            setSendTime(delivery.getSendTime());
//        }});
        int i = 0;
        Check check = new Check();
        if (checks != null && !checks.isEmpty()) {
            check = checks.get(0);
            i = 1;
        } else {
            check.setCreateTime(DateUtils.getNowDate());
            check.setDeptId(delivery.getDeptId());
            check.setUserId(delivery.getUserId());
            check.setSchoolId(delivery.getSchoolId());
            check.setOrderId(req.getDoseId());
            check.setSendTime(delivery.getSendTime());
            check.setLogId(delivery.getLogId());
            check.setStatus(req.getStatus());
            check.setDeliveryId(req.getDeliveryId());
            check.setDetailId(req.getId());
            i = checkMapper.insertCheck(check);
        }

        CheckDetail checkDetail = new CheckDetail();
        checkDetail.setCheckId(check.getId());
        checkDetail.setTypeId(req.getTypeId());
        checkDetail.setSpecId(req.getSpecId());
        checkDetail.setBrandId(req.getBrandId());
        checkDetail.setNum(req.getNum());
        checkDetail.setRealNum(req.getShouNum());
        checkDetail.setShouNum(req.getShouNum());
        checkDetail.setCreateTime(DateUtils.getNowDate());
        checkDetail.setProveFile(req.getProveFile());
        checkDetail.setDetailId(req.getId());
        checkDetailMapper.insertCheckDetail(checkDetail);

        Long noCompleteCount = checkDetailMapper.checkDetailCount(check_search);
        if (noCompleteCount > 0L) {
            check.setStatus(2);
            checkMapper.updateCheck(check);
        }

        //修改关联记录的数量
        DeliveryDetail deliveryDetail = deliveryDetailMapper.selectDeliveryDetailById(req.getId());

        BigDecimal weiNum = deliveryDetail.getWeiNum();

        deliveryDetail.setShouNum(deliveryDetail.getShouNum().add(req.getNum()));
        deliveryDetail.setWeiNum(deliveryDetail.getWeiNum().subtract(req.getNum()));

        if (deliveryDetail.getShouNum().compareTo(deliveryDetail.getNum()) > 0) {
            throw new ServiceException("本次验收数量大于未收货数量，未收货数量：" + weiNum
                    + "本次验收数量：" + req.getNum());
        }
        deliveryDetail.setStatus(1);
        deliveryDetail.setProveFile(req.getProveFile());

        deliveryDetailMapper.updateDeliveryDetail(deliveryDetail);

        return i;

    }

    /**
     * 修改验收
     *
     * @param check 验收
     * @return 结果
     */
    @Override
    @Transactional
    public int updateCheck(Check check) {

        if (check.getDetails() == null || check.getDetails().isEmpty()) {
            throw new ServiceException("没有验收物品");
        }

        int i = checkMapper.updateCheck(new Check() {{
            setId(check.getId());
            setStatus(check.getStatus());
            setUpdateTime(DateUtils.getNowDate());
        }});

        check.getDetails().forEach(item -> {
            checkDetailMapper.updateCheckDetail(new CheckDetail() {{
                setId(item.getId());
                setRealNum(item.getRealNum());
            }});
        });


        return i;
    }

    /**
     * 批量删除验收
     *
     * @param ids 需要删除的验收主键
     * @return 结果
     */
    @Override
    public int deleteCheckByIds(Long[] ids) {
        return checkMapper.deleteCheckByIds(ids);
    }

    /**
     * 删除验收信息
     *
     * @param id 验收主键
     * @return 结果
     */
    @Override
    public int deleteCheckById(Long id) {
        return checkMapper.deleteCheckById(id);
    }
}
